package com.zhisheng.orders.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhisheng.orderItem.entity.OrderItems;
import com.zhisheng.orders.feign.ProductsFeign;
import com.zhisheng.orders.mapper.OrderItemsMapper;
import com.zhisheng.orders.service.OrderItemsService;
import com.zhisheng.products.entity.Products;
import com.zhisheng.result.MyResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * (OrderItems)表服务实现类
 *
 * @author 全哥
 * @since 2025-02-24 14:49:24
 */
@Service("orderItemsService")
public class OrderItemsServiceImpl extends ServiceImpl<OrderItemsMapper, OrderItems> implements OrderItemsService {

    @Autowired
    private ProductsFeign productsFeign;

    @Override
    public void mySaveOrderItem(Map<Long, Integer> goods, Long id) {
        /*
            1: 将map集合中的所有数据转成OrderItem对象并设置订单号,最终批量保存到数据库中
         */
        List<OrderItems> list = goods.entrySet().stream().map(entry -> {
            // 把entry对象,转成 OrderItems
            OrderItems orderItems = new OrderItems(null,id,entry.getKey().intValue(), entry.getValue().intValue(),null,0,null );
            MyResponseResult<Products> productById = productsFeign.getProductById(orderItems.getProductId());
            double v = productById.getData().getPrice() * orderItems.getQuantity();
            orderItems.setUnitPrice(v);
            return orderItems;
        }).toList();
        saveBatch(list);
    }

    @Override
    public List<OrderItems> selectOrderItemsByOrderId(Long oid) {
        /*
            根据订单id,查询订单项列表
         */
        LambdaQueryWrapper<OrderItems> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItems::getOrderId, oid);
        List<OrderItems> list = list(queryWrapper);
        //  遍历list,根据list里面的每一个 OrderItems 对象中的 productId,调用商品服务,查询商品信息,将查询到的商品对象保存到 OrderItems 对象中
        list.forEach(orderItems -> {
            MyResponseResult<Products> productById = productsFeign.getProductById(orderItems.getProductId());
            orderItems.setProduct(productById.getData());
        });
        return list;
    }
}

